package web.tcp.test2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @description
 * @className TestClient
 * @package web.tcp.test2
 * @author dongww@hsyuntai.com
 * @date 2020/3/11 16:00
 * @copyright 版权归 HSYUNTAI 所有
 */
public class TestClient {

    InputStreamReader isr, isr2;
    BufferedReader br, br2;
    PrintWriter pw;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestClient tc = new TestClient();
    }

    public TestClient() {
        try {
            Socket s = new Socket("127.0.0.1", 3002);
            pw = new PrintWriter(s.getOutputStream(), true);
            //从控制台接收消息
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);

            //从服务器接收信息
            isr2 = new InputStreamReader(s.getInputStream());
            br2 = new BufferedReader(isr2);

            while (true) {
                System.out.println("请说出你想对服务器说的话，按回车键结束");
                //得到从控制台输入的消息
                String resp = br.readLine();
                //将数据发送给服务器
                pw.println(resp);
                if (resp.equals("再见")) {
                    System.out.println("客户端使对话结束");
                    s.close();
                    break;
                }


                String respo = br2.readLine();
                if (respo.equals("再见")) {
                    System.out.println("服务器使对话结束");
                    s.close();
                    break;
                }

                System.out.println("服务器说：" + respo);

            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (br2 != null) {
                try {
                    br2.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (isr2 != null) {
                try {
                    isr2.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (pw != null) {
                pw.close();
            }

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }
}